package com.personal.gateway.config;

import com.personal.gateway.custom.customEnum.DynamicEnumInterface;
import com.personal.gateway.custom.customEnum.flinkCommandEnum.FlinkVersionEnum;
import com.personal.gateway.utils.DynamicEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author BigHead
 * @date 2021/12/29 13:21
 * @description FlinkVersionConfig
 */

@Slf4j
@Configuration
public class FlinkVersionConfig implements DynamicEnumInterface {

    @Value("${flink.version.path:/flink.version}")
    private String flinkVersionPath;

    /**
     * 根据路径 查找所有flink的版本数据
     *
     * @return 版本名称 -> 绝对路径
     */
    public Map<String, String> getAllFlinkPath() {
        Map<String, String> flinkVersionPathMap = new HashMap<>();
        try {
            File flinkVersionPathFile = new File(flinkVersionPath);
            if (flinkVersionPathFile.isDirectory()) {
                for (File versionFile : Objects.requireNonNull(flinkVersionPathFile.listFiles())) {
                    if (versionFile.isDirectory()) {
                        flinkVersionPathMap.put(
                                versionFile.getName(),
                                versionFile.getCanonicalPath()
                        );
                    }
                }
            }
        } catch (IOException e) {
            log.error("", e);
        }
        return flinkVersionPathMap;
    }

    @Override
    public void flushEnum() {
        Map<String, String> flinkVersionPathMap = getAllFlinkPath();
        for (Map.Entry<String, String> entry : flinkVersionPathMap.entrySet()) {
            boolean hasEnum = false;
            for (FlinkVersionEnum flinkVersionEnum : FlinkVersionEnum.values()) {
                if (flinkVersionEnum.checkExist(entry.getKey())) {
                    hasEnum = true;
                }
            }
            if (!hasEnum) {
                DynamicEnumUtil.addEnum(
                        FlinkVersionEnum.class,
                        entry.getKey(),
                        new Class[]{String.class, String.class},
                        new Object[]{entry.getKey(), entry.getValue()}
                );
            }
        }
    }
}
